/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package routing;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Paweł
 */
public class PasswordStore {
    
    private final String filename = "./commdatpsu.data";

    private Map<String, byte[]> userPasswds;

    public PasswordStore() {
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
            userPasswds = (Map<String, byte[]>) ois.readObject();
            ois.close();
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            userPasswds = new HashMap<String, byte[]>();
        }
    }

    public void insert(String username, String password) {
        try {
            byte[] passwdSHA = SHA1(password);
            userPasswds.put(username, passwdSHA);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
            oos.writeObject(userPasswds);
            oos.close();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public void remove(String username) {
        userPasswds.remove(username);
    }

    public boolean check(String username, String password) {
        return Arrays.equals(userPasswds.get(username), SHA1(password));
    }

    private byte[] SHA1(String s) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA1");
            md.reset();
            md.update(s.getBytes());
            return md.digest();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(PasswordStore.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }
}
